package com.boarsoft.rpc.bean;

import java.io.Serializable;

import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.Util;
import com.boarsoft.common.util.HttpClientUtil;
import com.boarsoft.common.util.StringUtil;
import com.boarsoft.rpc.RpcConfig;
import com.boarsoft.rpc.util.XmlConfigUtil;

public class RpcNodeConfig implements Serializable {
	public static final long serialVersionUID = -238430885029993755L;
	private static final Logger log = LoggerFactory.getLogger(RpcNodeConfig.class);

	protected String address;
	protected String host;
	protected int port;
	protected boolean isMaster;

	/** 用于暂存 http://www.master.com:8080 这样的域名 */
	protected String url;

	public RpcNodeConfig() {
	}

	public RpcNodeConfig(Node n) {
		String addr = XmlConfigUtil.getStringAttr(n, "@address", null);
		this.setAddress(addr);
		this.isMaster = XmlConfigUtil.getBooleanAttr(n, "@master", false);
	}

	public String getAddress() {
		return this.address;
	}

	public void setAddress(String address) {
		if (StringUtil.isEmpty(address)) {
			throw new RuntimeException("Node address can not be blank.");
		}
		if ("myself".equalsIgnoreCase(address)) {
			address = RpcConfig.getAddr();
		} else if (address.startsWith("myip:")) {
			address = address.replace("myip", RpcConfig.getIp());
		} else if ("${rpc.registry.address}".equals(address)) {
			address = System.getProperty("rpc.registry.address");
		}
		if (address.startsWith("http://")) {
			this.url = address;
			// Map<String, List<String>> hm = HttpClientUtil.sendHead(address);
			// address = hm.get("addr").get(0);
			// System.out.println(hm.get(null));
			address = HttpClientUtil.sendGet(url, "");
			if (Util.strIsEmpty(address)) {
				log.warn("Get invalid master host {} from {}", address, url);
				return;
			}
			log.warn("Get master host {} from {}", address, url);
		}
		try {
			String[] a = address.split(":");
			this.host = a[0];
			this.port = Integer.parseInt(a[1]);
		} catch (Exception e) {
			log.error("Invalid master host = {}", address);
		}
		this.address = address;
	}

	public boolean isMaster() {
		return this.isMaster;
	}

	public void setMaster(boolean isMaster) {
		this.isMaster = isMaster;
	}

	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}

	public String getUrl() {
		return url;
	}

}
